package com.lihepeng.leecode.mulitithread;

import java.util.concurrent.LinkedBlockingQueue;

/**
 * 使用阻塞队列完成上面需求
 * 声明两个阻塞队列，一个存放打印foo 一个存放打印bar
 *
 * @author eloancn
 */
public class FooBar01 {
    private int n;
    private LinkedBlockingQueue<Integer> fooQueue;
    private LinkedBlockingQueue<Integer> barQueue;


    public FooBar01(int n) {
        this.n = n;
        fooQueue = new LinkedBlockingQueue<>();
        barQueue = new LinkedBlockingQueue<>();
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            barQueue.take();
            printFoo.run();
            barQueue.put(1);
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            fooQueue.take();
            printBar.run();
            fooQueue.put(1);
        }
    }
}
